package com.seezoon.domain.service.user;

import com.seezoon.domain.dao.mapper.UserInfoMapper;
import com.seezoon.domain.dao.po.UserInfoPO;
import com.seezoon.domain.service.user.vo.LoginTokenVO;
import com.seezoon.domain.service.user.vo.UserStatus;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.exception.ExceptionFactory;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 登录服务
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Validated
public class LoginService {

    private final LoginTokenService loginTokenService;
    private final UserInfoMapper userInfoMapper;

    /**
     * 用户名登录
     *
     * @param userName
     * @return
     */
    @Transactional
    public LoginTokenVO loginByUserName(@NotEmpty String userName) {
        UserInfoPO userPO = userInfoMapper.selectByUsername(userName);
        if (userPO == null) {
            throw ExceptionFactory.bizException(ErrorCode.USER_NOT_EXISTS);
        }
        Byte userStatus = userPO.getStatus();
        // 停用
        if (UserStatus.inValid(userStatus)) {
            throw ExceptionFactory.bizException(ErrorCode.USER_STATUS_INVALID);
        }
        // 锁定
        if (UserStatus.isLocked(userStatus)) {
            throw ExceptionFactory.bizException(ErrorCode.USER_STATUS_LOCKED);
        }
        return loginTokenService.createToken(userPO.getUid(), userPO.getSecretKey());
    }

    public void logout(@NotNull Long uid) {
        loginTokenService.logout(uid);
    }

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     */
    public LoginTokenVO refresh(@NotEmpty String refreshToken) {
        return this.loginTokenService.refreshToken(refreshToken);
    }

}
